<?php
namespace app\common\model;
use think\Model;
use think\Db;
class Base extends Model{
    public function _initialize(){
        parent::_initialize();
    }

    /**
     * 处理搜索条件
     * @param array $intkeys	条件为整数
     * @param array $strkeys	提交为字符串
     * @param array $randkeys	范围搜索	$randkeys = array(array('strtotime','addtime1'),array('strtotime','addtime2'))
     * @param array $likekeys	模糊搜索
     * @param array $inkeys		in搜索
     * @param array $pre		表的前缀
     */
    static public function buildSearch($intkeys=[], $strkeys=[], $randkeys=[], $likekeys=[],$inkeys=[],$pre = ''){
        $wherearr = [];
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        foreach ( $intkeys as $var ) {
            // $value = input('param.'.$var);
            $value = !empty($input[$var])||( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value !== ''){//不为空 但是可以为0
                $wherearr[] = "{$pre}{$var}='" . intval ( $value ) . "'";
            }
        }
        foreach ( $strkeys as $var ) {
            //$value = input('param.'.$var);
            $value = !empty($input[$var])||( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value != ''){
                //$wherearr [] = "{$pre}{$var}='$value'";
                //wangruifang
                $wherearr[] = "{$pre}{$var}='".self::param_filter($value)."'";
            }
        }

        foreach ( $randkeys as $vars ) {
            $value1=!empty($input[$vars['1'].'1'])?$input[$vars['1'].'1']:'';
            $value2=!empty($input[$vars['1'].'2'])?$input[$vars['1'].'2']:'';
            if(!empty($value1)){
                $wherearr[] = "{$pre}{$vars['1']}>='".$vars['0']($value1)."'";
            }
            if(!empty($value2)){
                $wherearr[] = "{$pre}{$vars['1']}<='".$vars['0']($value2)."'";
            }
        }


        foreach ( $likekeys as $var ) {
            if(!empty($input[$var])){
                $value_arr = explode (' ',$input[$var]);
                if(count($value_arr) == '1' && $value_arr ['0'] !== ''){
                    //echo json_encode($value_arr[0]);exit;
                    $value = strip_search_key(self::param_filter($value_arr['0']));
                    $where = "{$pre}{$var} LIKE '%$value%'";
                }else{
                    $where = '(';
                    foreach($value_arr as $v){
                        if($v !== ''){
                            $v = strip_search_key(self::param_filter($v['0']));
                            $where .= "{$pre}{$var} LIKE '%$v%' or ";
                        }
                    }
                    $where = substr ( $where, 0, - 4 ) . ")";
                }
                $wherearr[] = $where;
            }
        }
        foreach($inkeys as $var){
            $value = !empty($input[$var]) || ( isset($input[$var]) && $input[$var]==0)?$input[$var]:'';
            if($value != ''){//不为空 但是可以为0
                if(is_array($value)){
                    $val_arr = implode ( ',', $value );
                }else{
                    $val_arr = $value;
                }
                $wherearr [] = "{$pre}{$var} in (" . $val_arr . ")";
            }
        }
        return $wherearr?' AND '.implode(' AND ',$wherearr):'';
    }


    /****
     * 排序组装
     * @param string $sort
     * @param string $order
     * @return mixed
     */
    static public function list_param($sort='addtime', $order = 'desc') {
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        $result['sort'] = !empty( $input ['sort'])?$input ['sort']:$sort;
        $sort = explode(',',$result['sort']);
        $result['order'] = !empty($input['order'])?$input['order']:$order;
        $order = explode(',',$result['order']);
        $result['order_str'] = '';
        foreach($sort as $key => $v){
            $order[$key] = !empty($order[$key])?$order[$key]:'desc';
            $result['order_str'].= $v.' '.$order[$key].',';
        }
        $result['order_str'] = rtrim($result['order_str'],',');
        $result ['page'] = !empty($input['page'])?$input['page']:1;
        $result ['rows'] = !empty($input['rows'])?$input['rows']:20;
        return $result;
    }

    /****
     * 用于分类排序组装
     * @param string $sort
     * @param string $order
     * @return mixed
     */
    static public function list_param1($sort='addtime', $order = 'desc') {
        $inputJSON = file_get_contents('php://input');
        $input = json_decode($inputJSON, TRUE);
        $result['sort'] = !empty( $input ['sort'])?$input ['sort']:$sort;
        $sort = explode(',',$result['sort']);
        $result['order'] = !empty($input['order'])?$input['order']:$order;
        $order = explode(',',$result['order']);
        $result['order_str'] = '';
        foreach($sort as $key => $v){
            $result['order_str'].= $v.' '.$order[$key].',';
        }
        $result['order_str'] = rtrim($result['order_str'],',');
        return $result;
    }

    /****
     * 设置数据库表默认值
     * @param array $auto
     * @param array $data
     * @return array
     */
    static public function default_value($auto=[],$data=[]){
        if(!empty($auto) && !empty($auto)){
            foreach($auto as $key=>$value){
                if(!isset($data[$key])){
                    $data[$key] = $value;
                }
            }
        }
        return $data;
    }


    /***********
     * 字段检测
     * @param string $table 数据表名
     * @param $data 数据
     * @param $field 默认是连库查询，有字段则根据字段匹配
     * @return mixed
     */
    static public function allow_field($table='link',$data,$field=[],$config = []){
        // 检测字段
        if(empty($config)){
            $config = config('database.db_config1');
        }
        if(empty($field) && isset($table)){
            $field = Db::connect($config)->name($table)->getTableInfo('', 'fields');
        }
        if (!empty($field) && !empty($data)) {
            foreach ($data as $key => $val) {
                if (!in_array($key, $field)) {
                    unset($data[$key]);
                }
            }
        }
        return $data;
    }
    /**
     * @param mixed $data
     * @param array|string $type
     * @return mixed
     * 数据类型转换   $data 一维数组
     * $type 定义每个字段的类型
     */
    static public function format_conversion($data, $type){
        foreach($type as $k=>$v){
            if (is_array($v)) {
                list($v, $param) = $v;
            } elseif (strpos($v, ':')) {
                list($v, $param) = explode(':', $v, 2);
            }
            if(!empty($data[$k]) || isset($data[$k])){
                switch ($v) {
                    case 'integer':
                        $data[$k] = (int) $data[$k];
                        break;
                    case 'float':
                        if (empty($param)) {
                            $data[$k] = (float) $data[$k];
                        } else {
                            $data[$k] = (float) number_format($data[$k], $param);
                        }
                        break;
                    case 'boolean':
                        $data[$k] = (bool) $data[$k];
                        break;
                    case 'timestamp':
                        if (!is_null($data[$k])) {
                            $format = !empty($param) ? $param : 'Y-m-d H:i:s';
                            $data[$k]  = date($format, $data[$k]);
                        }
                        break;
                    case 'datetime':
                        if (!is_null($data[$k])) {
                            $format = !empty($param) ? $param : 'Y-m-d H:i:s';
                            $data[$k]  = date($format, strtotime($data[$k]));
                        }
                        break;
                    case 'json':
                        $data[$k] = json_decode($data[$k], true);
                        break;
                    case 'array':
                        $data[$k] = is_null($data[$k]) ? [] : json_decode($data[$k], true);
                        break;
                    case 'object':
                        $data[$k] = empty($data[$k]) ? new \stdClass() : json_decode($data[$k]);
                        break;
                    case 'serialize':
                        $data[$k] = unserialize($data[$k]);
                        break;
                }
            }
        }
        return $data;
    }

    /**
     * 发送短信
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function sendCode($data){
            $code = rand(111111, 999999); //验证码
            // $code = 2017; //固定验证码
            //查询条件
           $alisms = new \alisms\AlismsHandler();
            $rs = $alisms->sendSingleSms($data['mobile'],['code'=>$code]);
            if ($rs['status'] == 1) {
                $map=[
                    'val'=>$data['mobile'],
                    'web_id'=>!empty($data['web_id'])?$data['web_id']:0,
                    'lang_id'=>!empty($data['lang_id'])?$data['lang_id']:0,
                    'uid'=>!empty($data['uid'])?$data['uid']:0
                ];
                $sms = $map+[
                        'code'      => md5($code),
                        'addtime'   => time(),
                        'web_id'=>!empty($data['web_id'])?$data['web_id']:0,
                        'lang_id'=>!empty($data['lang_id'])?$data['lang_id']:0,
                        'uid'=>!empty($data['uid'])?$data['uid']:0
                    ];
                try{
                    $codeinfo = Db::connect(config('database.db_config1'))->name('SmsCheckCode')->where($map)->find();
                    if (!$codeinfo) {
                         Db::connect(config('database.db_config1'))->name('SmsCheckCode')->insert($sms);
                    } else {
                      Db::connect(config('database.db_config1'))->name('SmsCheckCode')->where($map)->update($sms);
                    }
                    return 10603;
                }catch (\Exception $e){
                    return -10682;
                }
            } else {
                return -10682;
            }
    }

    /**
     * @param string $data
     * @return string
     * wangruifang 0425
     */
    public static function param_filter($data=''){
        if(is_string($data) && !empty($data)){
            // 判断magic_quotes_gpc是否为打开
            if (!get_magic_quotes_gpc()){
                $data = addslashes($data); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤
            }
            //$data = strtr($data,array('_'=>'＼_','%'=>'＼%')); //把 '_' 和 ' % ' 过滤掉
            $data = strtr($data,array('%'=>'＼%')); //把 '_' 和 ' % ' 过滤掉
            $data = nl2br($data); // 回车转换
            $data= htmlspecialchars($data); // html标记转换
        }
        return $data;
    }
    
}